package com.wensi.lib_voice.asr

import android.content.Context
import com.baidu.speech.EventListener
import com.baidu.speech.EventManager
import com.baidu.speech.EventManagerFactory
import com.baidu.speech.asr.SpeechConstant
import org.json.JSONObject

/**
 * 语音识别
 */
object VoiceAsr {
    // 语音识别对象
    private lateinit var asr: EventManager
    private lateinit var wakeupJson: String

    fun initAsr (context: Context, listener: EventListener) {
        val map = HashMap<Any, Any>()
        // String json ="{
        // \"accept-audio-data\":false,
        // \"disable-punctuation\":false,
        // \"accept-audio-volume\":true,
        // \"pid\":1736
        // }"
        map[SpeechConstant.ACCEPT_AUDIO_DATA] = false
        map[SpeechConstant.ACCEPT_AUDIO_VOLUME] = true
        map[SpeechConstant.DISABLE_PUNCTUATION] = false
        map[SpeechConstant.PID] = 15373 // 普通话	输入法模型	加强标点（逗号、句号、问号、感叹号）	支持通用场景语义解析
        // 转换成json
        wakeupJson = JSONObject(map as Map<Any, Any>).toString()

        asr = EventManagerFactory.create(context, "asr")
        asr.registerListener(listener)
    }
    // 开始识别短语音
    fun startAsr() {
        asr.send(SpeechConstant.ASR_START, wakeupJson, null, 0, 0)
    }
    fun stopAsr() {
        asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0)
    }
    // 取消识别短语音
    fun cancelAsr() {
        asr.send(SpeechConstant.ASR_CANCEL, null, null, 0, 0)
    }
    fun releaseAsr(listener: EventListener) {
        asr.unregisterListener(listener)
    }
}